package com.heny.demo.dbutils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

/**
 * @author litao.cc
 * @version DeviceHistoryDataTableCreator.java v0.1 t2025/5/5 21:25
 * @date 2025/5/5 21:25
 * @description 设备历史数据表创建
 */
@Service("deviceHistoryDataTableCreator")
public class DeviceHistoryDataTableCreator implements TableCreator{

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Override
    public void createTableIfAbsent(DynamicTableProcessorEnum t, DynamicTableModel p) {
        String tableName = t.getProcessor().getTableName(p);
        String checkSql = String.format(
                "SELECT to_regclass('%s') IS NOT NULL AS exists;",
                tableName
        );
        String res = jdbcTemplate.queryForObject(checkSql, String.class);
        if(res.equals("f")){
            String createSql = 
                    "CREATE TABLE   tableName (  " +
                            "    id SERIAL  PRIMARY KEY,                                      " +
                            "    dev_id BIGINT NOT NULL,                                     " +
                            "    sn VARCHAR(255) NOT NULL,                                   " +
                            "    data_item_map text,                                        " +
                            "    sync_time TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,   " +
                            "    device_status VARCHAR(255)                                  " +
                            ");  " +
                            "  " +
                            "COMMENT ON TABLE   tableName IS '设备数据表';  " +
                            "COMMENT ON COLUMN   tableName.id IS '主键ID，自增';  " +
                            "COMMENT ON COLUMN   tableName.dev_id IS '设备编号';  " +
                            "COMMENT ON COLUMN   tableName.sn IS '设备SN号';  " +
                            "COMMENT ON COLUMN   tableName.data_item_map IS '设备实时数据，存储为JSON格式';  " +
                            "COMMENT ON COLUMN   tableName.sync_time IS '同步时间，默认当前时间，带时区';  " +
                            "COMMENT ON COLUMN   tableName.device_status IS '设备状态';";
            jdbcTemplate.execute(createSql.replaceAll("tableName", tableName));
        }


    }
}
